<template>
  <div class="customer-management">
    <!-- 页面头部导航区 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>CRM系统</el-breadcrumb-item>
            <el-breadcrumb-item>客户档案管理</el-breadcrumb-item>
            <el-breadcrumb-item>客户列表</el-breadcrumb-item>
          </el-breadcrumb>
          <h1>客户档案管理</h1>
          <p>管理中老年旅游客户的完整档案信息</p>
        </div>
        <div class="header-actions">
          <el-button type="default" :icon="Download">
            导出客户
          </el-button>
          <el-button type="default" :icon="Upload">
            批量导入
          </el-button>
          <el-button type="primary" :icon="Plus" @click="createCustomer">
            新增客户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 客户统计卡片区 -->
    <div class="statistics-section">
      <div class="stat-cards">
        <div class="stat-card total-customers">
          <div class="stat-icon">👥</div>
          <div class="stat-content">
            <div class="stat-number">{{ statistics.total }}</div>
            <div class="stat-trend">+{{ statistics.growth }} <span class="trend-text">较上月增长2.6%</span></div>
            <div class="stat-label">总客户数</div>
          </div>
        </div>

        <div class="stat-card active-customers">
          <div class="stat-icon">✅</div>
          <div class="stat-content">
            <div class="stat-number">{{ statistics.active }}</div>
            <div class="stat-percentage">({{ activePercentage }}%)</div>
            <div class="stat-label">有效客户</div>
          </div>
        </div>

        <div class="stat-card potential-customers">
          <div class="stat-icon">🎯</div>
          <div class="stat-content">
            <div class="stat-number">{{ statistics.potential }}</div>
            <div class="stat-percentage">({{ potentialPercentage }}%)</div>
            <div class="stat-label">潜在客户</div>
          </div>
        </div>

        <div class="stat-card health-status">
          <div class="stat-icon">💪</div>
          <div class="stat-content">
            <div class="health-chart">
              <div class="health-bar">
                <div class="health-segment good" :style="{ width: healthDistribution.good + '%' }"></div>
                <div class="health-segment normal" :style="{ width: healthDistribution.normal + '%' }"></div>
                <div class="health-segment poor" :style="{ width: healthDistribution.poor + '%' }"></div>
                <div class="health-segment bad" :style="{ width: healthDistribution.bad + '%' }"></div>
              </div>
            </div>
            <div class="stat-label">健康状况分布</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选控制区 -->
    <div class="search-filter-section">
      <el-row :gutter="16" align="middle">
        <!-- 搜索框 -->
        <el-col :xs="24" :sm="12" :md="10" :lg="8">
          <el-input
              v-model="searchKeyword"
              placeholder="搜索客户姓名、手机号或客户编号"
              :prefix-icon="Search"
              @input="handleSearch"
              clearable
          />
        </el-col>

        <!-- 筛选控件 -->
        <el-col :xs="24" :sm="12" :md="14" :lg="16">
          <div class="filter-controls">
            <el-select v-model="filters.customerStatus" placeholder="客户状态" clearable>
              <el-option label="有效客户" value="有效客户" />
              <el-option label="潜在客户" value="潜在客户" />
              <el-option label="无效客户" value="无效客户" />
              <el-option label="已成交客户" value="已成交客户" />
              <el-option label="黑名单" value="黑名单" />
            </el-select>

            <el-select v-model="filters.healthStatus" placeholder="健康状况" clearable>
              <el-option label="健康良好" value="健康良好" />
              <el-option label="健康一般" value="健康一般" />
              <el-option label="健康较差" value="健康较差" />
              <el-option label="健康很差" value="健康很差" />
            </el-select>

            <el-select v-model="filters.ageRange" placeholder="年龄范围" clearable>
              <el-option label="50-60岁" value="50-60" />
              <el-option label="60-70岁" value="60-70" />
              <el-option label="70-80岁" value="70-80" />
              <el-option label="80岁以上" value="80+" />
            </el-select>

            <el-button @click="resetFilters">重置筛选</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 激活筛选标签 -->
      <el-row v-if="hasActiveFilters" style="margin-top: 16px;">
        <el-col :span="24">
          <div class="active-filters">
            <el-tag
                v-for="filter in activeFilters"
                :key="filter.key"
                closable
                @close="removeFilter(filter.key)"
                type="primary"
            >
              {{ filter.label }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar-section">
      <el-row :gutter="16" justify="space-between" align="middle">
        <!-- 左侧控制区 -->
        <el-col :xs="24" :sm="14" :md="12" :lg="10">
          <div class="toolbar-left">
            <el-radio-group v-model="viewMode" size="default">
              <el-radio-button value="card">卡片视图</el-radio-button>
              <el-radio-button value="table">表格视图</el-radio-button>
            </el-radio-group>

            <el-select v-model="sortBy" placeholder="排序方式">
              <el-option label="创建时间" value="createdAt" />
              <el-option label="姓名" value="name" />
              <el-option label="年龄" value="age" />
              <el-option label="最近联系" value="lastContact" />
            </el-select>
          </div>
        </el-col>

        <!-- 右侧操作区 -->
        <el-col :xs="24" :sm="10" :md="12" :lg="14">
          <div class="toolbar-right">
            <div class="batch-actions" v-if="selectedCustomers.length">
              <el-button size="small">批量更新状态</el-button>
              <el-button size="small">批量添加标签</el-button>
              <el-button size="small">批量导出</el-button>
              <el-button size="small" type="danger">批量删除</el-button>
            </div>
            <el-checkbox v-model="selectAll" @change="handleSelectAll">
              全选
            </el-checkbox>


          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 客户数据展示区 -->
    <div class="data-display-section">
      <!-- 卡片视图 -->
      <div v-if="viewMode === 'card'" class="card-view">
        <div class="customer-grid">
          <div
              v-for="customer in displayCustomers"
              :key="customer.id"
              class="customer-card"
              :class="{ selected: selectedCustomers.includes(customer.id) }"
          >
            <div class="card-status-bar" :class="getStatusClass(customer.customerStatus)"></div>

            <div class="card-header">
              <div class="customer-avatar">
                <el-avatar shape="square" :size="60" :src="customer.avatar" :icon="UserFilled" />
              </div>

              <div class="customer-basic">
                <div class="name-with-status">
                  <h3>{{ customer.customerName }}</h3>
                  <el-tag :type="getStatusTagType(customer.customerStatus)" size="small" style="margin-left: 8px;">
                    {{ customer.customerStatus }}
                  </el-tag>
                </div>
                <p>{{ customer.customerCode }} · {{ customer.age }}岁 · {{ customer.gender }}</p>
                <p class="phone">{{ customer.primaryPhone }}</p>
              </div>

              <div class="card-actions">
                <el-checkbox
                    :model-value="selectedCustomers.includes(customer.id)"
                    @change="handleSelectCustomer(customer.id, $event)"
                />
                <el-dropdown>
                  <el-button text :icon="More" />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :icon="Phone">拨号</el-dropdown-item>
                      <el-dropdown-item :icon="ChatDotSquare">短信</el-dropdown-item>
                      <el-dropdown-item :icon="Edit">编辑</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>

            <div class="card-body">
              <div class="customer-tags">
                <el-tag
                    v-for="tag in customer.tags.slice(0, 3)"
                    :key="tag.id || tag.name"
                    size="small"
                    type="info"
                >
                  {{ tag.name || tag }}
                </el-tag>
                <el-tag v-if="customer.tags.length > 3" size="small" type="info">
                  +{{ customer.tags.length - 3 }}
                </el-tag>
              </div>

              <div class="travel-preferences">
                <p><strong>目的地偏好：</strong>{{ customer.destinationPreference?.join('、') || '暂无' }}</p>
                <p><strong>预算范围：</strong>{{ customer.budgetRange || '暂无' }}</p>
              </div>

              <div class="health-info">
                <div class="health-status" :class="getHealthStatusClass(customer.healthStatus)">
                  <span class="health-icon">{{ getHealthIcon(customer.healthStatus) }}</span>
                  <span>{{ customer.healthStatus }}</span>
                </div>
              </div>
            </div>

            <div class="card-footer">
              <div class="contact-history">
                <p>最后联系：{{ formatDate(customer.lastContactTime) }}</p>
                <p>本月联系：{{ customer.monthlyContactCount }}次</p>
              </div>

              <div class="action-buttons">
                <el-button size="small" type="primary">立即联系</el-button>
                <el-button size="small">安排跟进</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格视图 -->
      <div v-else class="table-view">
        <el-table :data="displayCustomers" style="width: 100%" stripe>
          <el-table-column type="selection" width="55" />

          <el-table-column fixed prop="customerCode" label="客户编号" width="130" />

          <el-table-column prop="customerName" label="姓名" width="120" />

          <el-table-column prop="gender" label="性别" width="80" />

          <el-table-column prop="age" label="年龄" width="80" />

          <el-table-column prop="primaryPhone" label="联系方式" width="140" />

          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.customerStatus)" size="small">
                {{ row.customerStatus }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="健康状况" width="100">
            <template #default="{ row }">
              <el-tag :type="getHealthTagType(row.healthStatus)" size="small">
                {{ row.healthStatus }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="标签" width="200">
            <template #default="{ row }">
              <el-tag
                  v-for="tag in row.tags.slice(0, 2)"
                  :key="tag.id || tag.name"
                  size="small"
                  type="info"
                  style="margin-right: 4px;"
              >
                {{ tag.name || tag }}
              </el-tag>
              <el-tag v-if="row.tags.length > 2" size="small" type="info">
                +{{ row.tags.length - 2 }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="lastContactTime" label="最后联系" width="120">
            <template #default="{ row }">
              {{ formatDate(row.lastContactTime) }}
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" min-width="180">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="viewCustomer(row.id)">
                查看
              </el-button>
              <el-button link type="primary" size="small" @click="editCustomer(row.id)">
                编辑
              </el-button>
              <el-button link type="success" size="small" @click="callCustomer(row.primaryPhone)">
                拨号
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <div v-if="!displayCustomers.length && !loading" class="empty-state">
        <div class="empty-icon">👥</div>
        <h3>暂无客户数据</h3>
        <p>开始添加您的第一个客户档案</p>
        <el-button type="primary" :icon="Plus" @click="createCustomer">新增客户</el-button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>
    </div>

    <!-- 分页控制区 -->
    <div class="pagination-section" v-if="displayCustomers.length">
      <el-row justify="center">
        <el-col :span="24">
          <div class="pagination-wrapper">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[20, 50, 100, 200]"
                :total="total"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search, Plus, Download, Upload, More, Phone, ChatDotRound as ChatDotSquare, Edit, View,
  UserFilled
} from '@element-plus/icons-vue'
import { customerAPI } from '@/api/customer'
import type { CustomerBasicInfo } from '@/api/customer'
import { ElMessage } from 'element-plus'

// 路由
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const loading = ref(false)
const viewMode = ref<'card' | 'table'>('card')
const sortBy = ref('createdAt')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectAll = ref(false)
const selectedCustomers = ref<string[]>([])

// 筛选条件
const filters = ref({
  customerStatus: '',
  healthStatus: '',
  ageRange: ''
})

// 客户数据
const customers = ref<CustomerBasicInfo[]>([])

// 统计数据
const statistics = ref({
  total: 0,
  active: 0,
  potential: 0,
  growth: 0
})

// 计算属性
const activePercentage = computed(() =>
    Math.round((statistics.value.active / statistics.value.total) * 100)
)

const potentialPercentage = computed(() =>
    Math.round((statistics.value.potential / statistics.value.total) * 100)
)

const healthDistribution = computed(() => ({
  good: 45,
  normal: 30,
  poor: 20,
  bad: 5
}))

const hasActiveFilters = computed(() =>
    Object.values(filters.value).some(value => value !== '')
)

const activeFilters = computed(() => {
  const result = []
  if (filters.value.customerStatus) {
    result.push({ key: 'customerStatus', label: `状态: ${filters.value.customerStatus}` })
  }
  if (filters.value.healthStatus) {
    result.push({ key: 'healthStatus', label: `健康: ${filters.value.healthStatus}` })
  }
  if (filters.value.ageRange) {
    result.push({ key: 'ageRange', label: `年龄: ${filters.value.ageRange}` })
  }
  return result
})

const displayCustomers = computed(() => {
  let result = [...customers.value]

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(customer =>
        customer.customerName.toLowerCase().includes(keyword) ||
        customer.customerCode.toLowerCase().includes(keyword) ||
        customer.primaryPhone.includes(keyword)
    )
  }

  // 状态过滤
  if (filters.value.customerStatus) {
    result = result.filter(customer => customer.customerStatus === filters.value.customerStatus)
  }

  if (filters.value.healthStatus) {
    result = result.filter(customer => customer.healthStatus === filters.value.healthStatus)
  }

  // 年龄过滤
  if (filters.value.ageRange) {
    const [min, max] = filters.value.ageRange.split('-').map(Number)
    result = result.filter(customer => {
      if (filters.value.ageRange === '80+') {
        return customer.age >= 80
      }
      return customer.age >= min && customer.age <= max
    })
  }

  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'name':
        return a.customerName.localeCompare(b.customerName)
      case 'age':
        return b.age - a.age
      case 'lastContact':
        return new Date(b.lastContactTime).getTime() - new Date(a.lastContactTime).getTime()
      default:
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    }
  })

  return result
})

// 方法
const loadCustomers = async () => {
  try {
    loading.value = true
    const response = await customerAPI.getCustomerList({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      ...filters.value
    })

    customers.value = response.data.list
    total.value = response.data.pagination.total
  } catch (error) {
    ElMessage.error('加载客户数据失败')
    console.error('Load customers error:', error)
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await customerAPI.getStatisticsOverview()
    statistics.value = response.data
  } catch (error) {
    console.error('Load statistics error:', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadCustomers()
}

const resetFilters = () => {
  filters.value = {
    customerStatus: '',
    healthStatus: '',
    ageRange: ''
  }
  currentPage.value = 1
  loadCustomers()
}

const removeFilter = (key: string) => {
  filters.value[key as keyof typeof filters.value] = ''
  loadCustomers()
}

const handleSelectAll = (value: boolean) => {
  if (value) {
    selectedCustomers.value = displayCustomers.value.map(customer => customer.id)
  } else {
    selectedCustomers.value = []
  }
}

const handleSelectCustomer = (customerId: string, selected: boolean) => {
  if (selected) {
    selectedCustomers.value.push(customerId)
  } else {
    const index = selectedCustomers.value.indexOf(customerId)
    if (index > -1) {
      selectedCustomers.value.splice(index, 1)
    }
  }
}

const handleSelectionChange = (selection: CustomerBasicInfo[]) => {
  selectedCustomers.value = selection.map(customer => customer.id)
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadCustomers()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadCustomers()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadCustomers()
}

const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '有效客户': 'status-active',
    '潜在客户': 'status-potential',
    '无效客户': 'status-inactive',
    '已成交客户': 'status-completed',
    '黑名单': 'status-blacklist'
  }
  return statusMap[status] || 'status-default'
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '有效客户': '#34C759',
    '潜在客户': '#5AC8FA',
    '无效客户': '#8E8E93',
    '已成交客户': '#FF9500',
    '黑名单': '#FF3B30'
  }
  return colorMap[status] || '#8E8E93'
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '有效客户': 'success',
    '潜在客户': 'primary',
    '无效客户': 'info',
    '已成交客户': 'warning',
    '黑名单': 'danger'
  }
  return typeMap[status] || 'default'
}

const getHealthTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '健康良好': 'success',
    '健康一般': 'warning',
    '健康较差': 'danger',
    '健康很差': 'danger'
  }
  return typeMap[status] || 'info'
}

const getHealthStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '健康良好': 'health-good',
    '健康一般': 'health-normal',
    '健康较差': 'health-poor',
    '健康很差': 'health-bad'
  }
  return statusMap[status] || 'health-default'
}

const getHealthIcon = (status: string) => {
  const iconMap: Record<string, string> = {
    '健康良好': '💚',
    '健康一般': '💛',
    '健康较差': '🧡',
    '健康很差': '❤️'
  }
  return iconMap[status] || '💙'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) return '今天'
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`
  return `${Math.floor(diffDays / 30)}月前`
}

const viewCustomer = (customerId: string) => {
  // 查看客户详情
  router.push(`/customers/${customerId}`)
}

const createCustomer = () => {
  router.push('/customers/create')
}

const editCustomer = (customerId: string) => {
  router.push(`/customers/${customerId}/edit`)
}

const callCustomer = (phone: string) => {
  // 拨打电话
  window.open(`tel:${phone}`)
}

// 监听器
watch([filters, sortBy], () => {
  currentPage.value = 1
  loadCustomers()
}, { deep: true })

// 生命周期
onMounted(() => {
  loadCustomers()
  loadStatistics()
})
</script>

<style lang="scss" scoped>
.customer-management {
  padding: var(--apple-spacing-lg);
  background: var(--apple-background-primary);
  min-height: 100vh;

  // 页面头部
  .page-header {
    background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
    padding: var(--apple-spacing-xl);
    border-radius: var(--apple-radius-lg);
    margin-bottom: var(--apple-spacing-lg);
    color: white;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
    }

    .header-left {
      h1 {
        font-size: 2rem;
        font-weight: 700;
        margin: var(--apple-spacing-sm) 0;
      }

      p {
        opacity: 0.9;
        margin: 0;
      }

      :deep(.el-breadcrumb) {
        .el-breadcrumb__item {
          .el-breadcrumb__inner {
            color: rgba(255, 255, 255, 0.8);
            &:hover {
              color: white;
            }
          }
        }
        .el-breadcrumb__separator {
          color: rgba(255, 255, 255, 0.6);
        }
      }
    }

    .header-actions {
      display: flex;
      gap: var(--apple-spacing-sm);

      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }

        &.el-button--primary {
          background: white;
          color: #007AFF;

          &:hover {
            background: rgba(255, 255, 255, 0.9);
          }
        }
      }
    }
  }

  // 搜索筛选区域
  .search-filter-section {
    background: white;
    padding: 24px; /* fallback for var(--apple-spacing-lg) */
    border-radius: 12px; /* fallback for var(--apple-radius-lg) */
    margin-bottom: 24px; /* fallback for var(--apple-spacing-lg) */
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* fallback for var(--apple-shadow-md) */
    border: 1px solid #e5e5ea; /* 添加边框以确保可见性 */

    /* CSS 变量覆盖 */
    padding: var(--apple-spacing-lg, 24px);
    border-radius: var(--apple-radius-lg, 12px);
    margin-bottom: var(--apple-spacing-lg, 24px);
    box-shadow: var(--apple-shadow-md, 0 4px 6px rgba(0, 0, 0, 0.1));

    .filter-controls {
      display: flex;
      gap: 8px; /* fallback */
      gap: var(--apple-spacing-sm, 8px);
      justify-content: flex-end;
      flex-wrap: wrap;
      align-items: center;

      .el-select {
        width: 120px;
        flex-shrink: 0;
      }

      .el-button {
        white-space: nowrap;
        flex-shrink: 0;
      }
    }

    // 移动端适配
    @media (max-width: 768px) {
      .filter-controls {
        justify-content: flex-start;
        margin-top: 12px;

        .el-select {
          width: 110px;
        }
      }
    }

    @media (max-width: 576px) {
      .filter-controls {
        gap: 6px;

        .el-select {
          width: 100px;
        }
      }
    }

    .active-filters {
      margin-top: var(--apple-spacing-md);
      display: flex;
      gap: var(--apple-spacing-xs);
      flex-wrap: wrap;
    }
  }

  // 统计卡片区域
  .statistics-section {
    margin-bottom: 24px; /* fallback */
    margin-bottom: var(--apple-spacing-lg, 24px);

    .stat-cards {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px; /* fallback */
      gap: var(--apple-spacing-md, 16px);
      
      // 移动端响应式
      @media (max-width: 1200px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }
    }

    .stat-card {
      background: white;
      padding: 24px; /* fallback */
      border-radius: 12px; /* fallback */
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* fallback */
      border: 1px solid #e5e5ea; /* 添加边框以确保可见性 */

      /* CSS 变量覆盖 */
      padding: var(--apple-spacing-lg, 24px);
      border-radius: var(--apple-radius-lg, 12px);
      box-shadow: var(--apple-shadow-light, 0 1px 3px rgba(0, 0, 0, 0.1));
      display: flex;
      align-items: center;
      transition: transform 0.2s ease;
      border-top: 4px solid;

      &:hover {
        transform: translateY(-2px);
        box-shadow: var(--apple-shadow-medium);
      }

      &.total-customers {
        border-top-color: #007AFF;
      }

      &.active-customers {
        border-top-color: #34C759;
      }

      &.potential-customers {
        border-top-color: #5AC8FA;
      }

      &.health-status {
        border-top-color: #FF9500;
      }

      .stat-icon {
        font-size: 3rem;
        margin-right: var(--apple-spacing-md);
      }

      .stat-content {
        flex: 1;

        .stat-number {
          font-size: 2rem;
          font-weight: 700;
          color: var(--apple-text-primary);
          line-height: 1.2;
        }

        .stat-percentage {
          color: var(--apple-text-secondary);
          font-size: 0.9rem;
        }

        .stat-trend {
          color: #34C759;
          font-size: 0.9rem;
          margin: var(--apple-spacing-xs) 0;

          .trend-text {
            color: var(--apple-text-secondary);
            margin-left: var(--apple-spacing-xs);
          }
        }

        .stat-label {
          color: var(--apple-text-secondary);
          font-size: 0.9rem;
        }

        .health-chart {
          margin: var(--apple-spacing-xs) 0;

          .health-bar {
            height: 8px;
            border-radius: 4px;
            overflow: hidden;
            display: flex;
            background: #f0f0f0;

            .health-segment {
              height: 100%;

              &.good { background: #34C759; }
              &.normal { background: #FFCC00; }
              &.poor { background: #FF9500; }
              &.bad { background: #FF3B30; }
            }
          }
        }
      }
    }
  }

  // 工具栏
  .toolbar-section {
    background: white;
    padding: 16px; /* fallback */
    border-radius: 12px; /* fallback */
    margin-bottom: 16px; /* fallback */
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* fallback */
    border: 1px solid #e5e5ea; /* 添加边框以确保可见性 */

    /* CSS 变量覆盖 */
    padding: var(--apple-spacing-md, 16px);
    border-radius: var(--apple-radius-lg, 12px);
    margin-bottom: var(--apple-spacing-md, 16px);
    box-shadow: var(--apple-shadow-light, 0 1px 3px rgba(0, 0, 0, 0.1));

    .toolbar-left {
      display: flex;
      gap: 12px; /* fallback */
      gap: var(--apple-spacing-md, 12px);
      align-items: center;
      flex-wrap: wrap;

      .el-select {
        width: 120px;
        flex-shrink: 0;
      }

      .el-radio-group {
        flex-shrink: 0;
      }
    }

    .toolbar-right {
      display: flex;
      gap: 12px; /* fallback */
      gap: var(--apple-spacing-md, 12px);
      align-items: center;
      flex-wrap: wrap;
      justify-content: flex-end;

      .batch-actions {
        display: flex;
        gap: 6px; /* fallback */
        gap: var(--apple-spacing-xs, 6px);
        flex-wrap: wrap;
      }
    }

    // 移动端适配
    @media (max-width: 768px) {
      .toolbar-left,
      .toolbar-right {
        justify-content: flex-start;
      }

      .toolbar-right {
        margin-top: 12px;
      }

      .toolbar-left {
        .el-select {
          width: 100px;
        }
      }

      .batch-actions {
        .el-button {
          padding: 5px 8px;
          font-size: 12px;
        }
      }
    }

    @media (max-width: 576px) {
      .toolbar-left {
        gap: 8px;

        .el-select {
          width: 90px;
        }
      }

      .toolbar-right {
        gap: 8px;
      }
    }
  }

  // 数据展示区域
  .data-display-section {
    background: white;
    border-radius: var(--apple-radius-lg);
    box-shadow: var(--apple-shadow-light);
    overflow: hidden;

    // 卡片视图
    .card-view {
      padding: var(--apple-spacing-lg);

      .customer-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
        gap: var(--apple-spacing-lg);
      }

      .customer-card {
        border: 1px solid var(--apple-separator-primary);
        border-radius: var(--apple-radius-lg);
        overflow: hidden;
        transition: all 0.2s ease;
        position: relative;

        &:hover {
          transform: translateY(-2px);
          box-shadow: var(--apple-shadow-medium);
        }

        &.selected {
          border-color: #007AFF;
          box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
        }

        .card-status-bar {
          height: 4px;
          width: 100%;

          &.status-active { background: #34C759; }
          &.status-potential { background: #5AC8FA; }
          &.status-inactive { background: #8E8E93; }
          &.status-completed { background: #FF9500; }
          &.status-blacklist { background: #FF3B30; }
        }

        .card-header {
          padding: var(--apple-spacing-md);
          display: flex;
          align-items: flex-start;
          gap: var(--apple-spacing-md);

          .customer-avatar {
            position: relative;
          }

          .customer-basic {
            flex: 1;

            .name-with-status {
              display: flex;
              align-items: center;
              margin-bottom: var(--apple-spacing-xs);

              h3 {
                margin: 0;
                font-size: 1.1rem;
                font-weight: 600;
                color: var(--apple-text-primary);
              }
            }

            p {
              margin: 0;
              color: var(--apple-text-secondary);
              font-size: 0.9rem;

              &.phone {
                color: #007AFF;
                font-weight: 500;
              }
            }
          }

          .card-actions {
            display: flex;
            flex-direction: column;
            gap: var(--apple-spacing-xs);
          }
        }

        .card-body {
          padding: 0 var(--apple-spacing-md) var(--apple-spacing-md);

          .customer-tags {
            margin-bottom: var(--apple-spacing-md);
            display: flex;
            gap: var(--apple-spacing-xs);
            flex-wrap: wrap;
          }

          .travel-preferences {
            margin-bottom: var(--apple-spacing-md);

            p {
              margin: var(--apple-spacing-xs) 0;
              font-size: 0.9rem;
              color: var(--apple-text-secondary);

              strong {
                color: var(--apple-text-primary);
              }
            }
          }

          .health-info {
            .health-status {
              display: flex;
              align-items: center;
              gap: var(--apple-spacing-xs);
              font-size: 0.9rem;
              font-weight: 500;

              &.health-good { color: #34C759; }
              &.health-normal { color: #FFCC00; }
              &.health-poor { color: #FF9500; }
              &.health-bad { color: #FF3B30; }
            }
          }
        }

        .card-footer {
          padding: var(--apple-spacing-md);
          border-top: 1px solid var(--apple-separator-primary);
          background: var(--apple-background-secondary);
          display: flex;
          justify-content: space-between;
          align-items: center;

          .contact-history {
            p {
              margin: 0;
              font-size: 0.8rem;
              color: var(--apple-text-secondary);
            }
          }

          .action-buttons {
            display: flex;
            gap: var(--apple-spacing-xs);
          }
        }
      }
    }

    // 表格视图
    .table-view {
      .customer-info {
        display: flex;
        align-items: center;
        gap: var(--apple-spacing-sm);

        .info-text {
          .name {
            font-weight: 600;
            color: var(--apple-text-primary);
          }

          .details {
            font-size: 0.8rem;
            color: var(--apple-text-secondary);
          }
        }
      }

      .health-status {
        display: flex;
        align-items: center;
        gap: var(--apple-spacing-xs);
        font-size: 0.9rem;

        &.health-good { color: #34C759; }
        &.health-normal { color: #FFCC00; }
        &.health-poor { color: #FF9500; }
        &.health-bad { color: #FF3B30; }
      }

      .table-tags {
        display: flex;
        gap: var(--apple-spacing-xs);
        flex-wrap: wrap;
      }
    }

    // 空状态
    .empty-state {
      text-align: center;
      padding: var(--apple-spacing-xl) var(--apple-spacing-lg);

      .empty-icon {
        font-size: 4rem;
        margin-bottom: var(--apple-spacing-md);
      }

      h3 {
        color: var(--apple-text-primary);
        margin-bottom: var(--apple-spacing-sm);
      }

      p {
        color: var(--apple-text-secondary);
        margin-bottom: var(--apple-spacing-lg);
      }
    }

    // 加载状态
    .loading-state {
      padding: var(--apple-spacing-lg);
    }
  }

  // 分页区域
  .pagination-section {
    padding: 24px; /* fallback */
    background: white;
    border-radius: 12px; /* fallback */
    margin-top: 16px; /* fallback */
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* fallback */
    border: 1px solid #e5e5ea; /* 添加边框以确保可见性 */

    /* CSS 变量覆盖 */
    padding: var(--apple-spacing-lg, 24px);
    border-radius: var(--apple-radius-lg, 12px);
    margin-top: var(--apple-spacing-md, 16px);
    box-shadow: var(--apple-shadow-light, 0 1px 3px rgba(0, 0, 0, 0.1));

    .pagination-wrapper {
      display: flex;
      justify-content: center;

      .el-pagination {
        flex-wrap: wrap;
        justify-content: center;

        // 移动端适配
        @media (max-width: 768px) {
          .el-pagination__sizes,
          .el-pagination__total {
            margin-bottom: 8px;
          }
        }
      }
    }

    // 移动端完全居中
    @media (max-width: 576px) {
      padding: 16px;

      .pagination-wrapper {
        .el-pagination {
          .el-pagination__sizes .el-select {
            width: 80px;
          }
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: var(--apple-spacing-md);

    .page-header .header-content {
      flex-direction: column;
      gap: var(--apple-spacing-md);
      align-items: stretch;
    }


    .toolbar-section {
      flex-direction: column;
      align-items: stretch;

      .toolbar-left,
      .toolbar-right {
        justify-content: center;
      }
    }

    .card-view .customer-grid {
      grid-template-columns: 1fr;
    }

    .pagination-section {
      flex-direction: column;
      gap: var(--apple-spacing-md);
    }
  }
}
</style>